import { Ref, SetupContext } from "vue";
import { PopoverProps } from "../popover.props";
import { UsePosition, UseResize } from "./types";

export function useResize(
    props: PopoverProps,
    context: SetupContext,
    reference: Ref<any>,
    shouldFitWidthToReference: Ref<boolean>,
    positionComposition: UsePosition
): UseResize {

    const { popoverWidth, fitToReference, followToReferencePosition } = positionComposition;

    function onResize() {
        if (reference.value) {
            followToReferencePosition(reference.value);
            const referenceRect = reference.value.getBoundingClientRect() as DOMRect;
            if (shouldFitWidthToReference.value && referenceRect.width !== popoverWidth.value) {
                fitToReference(reference.value);
            }
        }
    }

    return { onResize };

}
